<template>
  <div class="page-container">
    <el-form class="base-search-form" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <!-- <el-form-item label="所属公司" prop="coId">
        <el-tree-select
          v-model="queryParams.coId"
          :data="companyList"
          :render-after-expand="true"
          :props="treeProps"
          node-key="id"
          check-strictly
          @change="handleCompanyChange"
        />
      </el-form-item> -->
      <!-- <el-form-item label="所属部门" prop="deptId">
        <el-select v-model="queryParams.departId" placeholder="请选择" :disabled="!queryParams.coId">
          <el-option
            v-for="dict in departList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="base-container mb-50px">
      <div class="flex mb-10px">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增</el-button>
        <!-- <el-button 
          plain type="danger" 
          icon="Delete" 
          @click="handleDelete" 
          v-hasPermi="['system:user:remove']">
          删除
        </el-button> -->
        <!-- <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button> -->
        <!-- <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button> -->
        <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </div>

      <el-table class="table" border v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" /> -->
        <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" /> -->
        <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
        <!-- <el-table-column label="所属公司" align="center" key="coName" prop="coName" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column label="所属部门" align="center" key="departName" prop="departName" :show-overflow-tooltip="true" /> -->
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" />
        <el-table-column label="状态" align="center" key="status">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              inline-prompt
              active-text="正常"
              inactive-text="停用"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <template v-if="scope.row.userId !== 1">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
              </el-tooltip>
              <el-tooltip content="重置密码" placement="top">
                <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
              </el-tooltip>
              <el-tooltip content="分配角色" placement="top">
                <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <Dialog v-model="showDialog" :title="dialogTitle">
      <edit-user 
        v-if="dialogType === 1" 
        ref="editUser" 
        :dept-options="deptOptions"
        @cancel="cancel"
        @confirm="confirm" />
      <upload-user 
        v-if="dialogType === 2"
        @cancel="cancel"
        @confirm="confirm"
      />
    </Dialog>
   </div>
</template>

<script setup name="User">
import { changeUserStatus, listUser, resetUserPwd, delUser, deptTreeSelect } from "@/api/system/user"
import { getAllCompanies } from '@/api/company/company'
import { listDepartment } from "@/api/company/department"
import { computed, nextTick } from "vue"
import EditUser from './edit.vue'
import UploadUser from './upload.vue'
import { md5 } from '@/utils/md5'

const editUser = ref()
const uploadUser = ref()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const companyList = ref([])
const departList = ref([])
const userList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const deptName = ref("")
const deptOptions = ref(undefined)
const showDialog = ref(false)
const dialogTitle = ref('')
const dialogType = ref(0)                 // 1新增编辑  2导入
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.check == false
  }
}

// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    coId: null,
    deptId: null,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },
})

const { queryParams } = toRefs(data)

const handleCompanyChange = () => {
  queryParams.value.deptId = null
  getDepartList()
}

/** 公司列表 */
const getCompanyList = () => {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

/** 部门列表 */
const getDepartList = () => {
  const params = {
    pageNum: 1,
    pageSize: 200,
    companyId: queryParams.value.coId
  }
  listDepartment(params).then(response => {
    departList.value = response.rows
  })
}

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除该用户？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/user/export", {
    ...queryParams.value,
  },`用户列表_${proxy.getFileImportName()}.xlsx`)
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用"
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0"
  })
}

/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId
  router.push("/system/user-auth/role/" + userId)
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{6,20}$/,
    inputErrorMessage: "用户密码长度必须介于 6 和 20 之间",
    inputValidator: (value) => {
      const reg = /^(((?=.*\d)(?=.*[a-zA-Z]))|((?=.*\d)(?=.*[\W_]))|((?=.*[a-zA-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]))).{6,20}$/
      if (!reg.test(value)) {
        return "用户密码需包含大小写字母、数字和特殊字符中的至少两种"
      }
    },
  }).then(({ value }) => {
    resetUserPwd(row.userId, md5(value)).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value)
    })
  }).catch(() => {})
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 导入按钮操作 */
function handleImport() {
  showDialog.value = true
  dialogTitle.value = '用户导入'
  dialogType.value = 2
}

/** 取消按钮 */
const cancel = () => {
  showDialog.value = false
  dialogTitle.value = ''
  dialogType.value = 0
}

/** 确认按钮 */
const confirm = () => {
  cancel()
  getList()
}

/** 新增按钮操作 */
const handleAdd = () => {
  showDialog.value = true
  dialogTitle.value = '添加用户'
  dialogType.value = 1
  nextTick(() => {
    editUser.value.pageInit()
  })
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  const userId = row.userId || ids.value
  showDialog.value = true
  dialogTitle.value = '修改用户'
  dialogType.value = 1
  nextTick(() => {
    editUser.value.pageInit(userId)
  })
}

// getCompanyList()
getList()
</script>

<style lang="scss" scoped>

</style>
